# python3

import random
import json

from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'
port = 1883
topic = "python/mqtt"
# Generate a Client ID with the subscribe prefix.
client_id = f'subscribe-{random.randint(0, 100)}'
# username = 'emqx'
# password = 'public'


def connect_mqtt() -> mqtt_client:
  def on_connect(client, userdata, flags, rc, properties):
    if rc == 0:
      print("Connected to MQTT Broker!")
    else:
      print("Failed to connect, return code %d\n", rc)

  client = mqtt_client.Client(client_id=client_id, callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2)
  # client.username_pw_set(username, password)
  client.on_connect = on_connect
  client.connect(broker, port)
  return client


def subscribe(client: mqtt_client):
  def on_message(client, userdata, msg):
    print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
    json_data = json.loads(msg.payload.decode())
    # print("parsed data:", json_data)
    print(f"`name`: {json_data['name']}, `age`: {json_data['age']}, `city`: {json_data['city']}")
    
  client.subscribe(topic)
  client.on_message = on_message


def run():
  client = connect_mqtt()
  subscribe(client)
  # client.loop_forever()
  client.loop_start()
  print("Waiting for messages...")
  try:
    while True:
      pass
  except KeyboardInterrupt:
    print("Exiting...")
    client.disconnect()
    client.loop_stop()

if __name__ == '__main__':
  run()
